//
//  VIncompleteContactVC.m
//  PrivatePhoto
//
//  Created by PrivatePhoto Team on 2021.
//  Copyright © 2021年 PrivatePhoto Team. All rights reserved.3.
//

#import "DYIncompleteContactVC.h"
#import "DYCommonSCell.h"
#import "YXContactsModel.h"
#import "DYCleanView.h"
#import "YXContactsRequestTool.h"
#import "PBSubscribeViewController.h"
#import "DYNoAllInfoManager.h"
@implementation IncompleteContactVCModel

- (instancetype)init{
    if (self == [super init]) {
        self.dataArray = [[NSMutableArray alloc] init];
        self.seletedPicArray = [[NSMutableArray alloc] init];
    }
    return self;
}

@end


@interface DYIncompleteContactVC ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, weak) UIButton *rightBtn;
@property (nonatomic, strong) DYCleanView *bottomView;
@property (nonatomic, strong) IncompleteContactVCModel *viewModel;
@end

@implementation DYIncompleteContactVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configSubView];
    [self configData];
    [self bindViewModel];
}

- (void)configSubView{
//    
//    self setNavigationItemTitleViewWithTitle:@"通讯录不完整";
//    self.gk_navRightBarButtonItem = [self rightBarButtonItem];
    self.tableView.frame = CGRectMake(0, self.navigationBarHeight, kScreenWidth, kScreenHeight-self.navigationBarHeight-kBottomSafeHeight);
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(-80);
        make.left.mas_offset(20);
        make.right.mas_offset(-20);
        make.height.mas_equalTo(64);
    }];
   
    self.bottomView.layer.cornerRadius = 32.f;
    self.bottomView.layer.masksToBounds = YES;
}

- (UIBarButtonItem *)rightBarButtonItem
{
    UIButton *button = [[UIButton alloc] init];
    [button setTitle:@"选择全部"forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithHexString:@"#528CFF"] forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 80, 22);
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [button addTarget:self action:@selector(rightBarButtonItemDidClick:) forControlEvents:UIControlEventTouchUpInside];
    button.selected = YES;
    self.rightBtn = button;
    return [[UIBarButtonItem alloc] initWithCustomView:button];
}

- (void)configData{
    [self.viewModel.dataArray removeAllObjects];
    if (kCANoAllInfoManager.dataList.count) {
        self.orginArray = kCANoAllInfoManager.dataList;
        self.viewModel.seletedPicArray = kCANoAllInfoManager.selectAry;
        self.viewModel.seletedCount = self.viewModel.seletedPicArray.count;
    }
    [self.viewModel.dataArray addObjectsFromArray:self.orginArray];
    [self.tableView reloadData];
}

- (void)bindViewModel{
    @weakify(self)
    [RACObserve(self, viewModel.seletedCount) subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        BOOL isSeletedAll = self.viewModel.seletedCount >= self.viewModel.dataArray.count;
        NSString *title = !isSeletedAll ? @"选择全部":@"取消全选";
        [self.rightBtn setTitle:title forState:UIControlStateNormal];
        if (!self.viewModel.seletedCount) {
            [self setNavigationItemTitleViewWithTitle:@"通讯录不完整"];
            self.bottomView.hidden = YES;
        }else{
            [self setNavigationItemTitleViewWithTitle:[NSString stringWithFormat:@"已选择%ld个联系人",(long)self.viewModel.seletedCount]];
            self.bottomView.hidden = NO;
        }
        
    }];
  
}

#pragma make --- tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.viewModel.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cell_Id = @"DYCommonSCell";
    DYCommonSCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_Id];
    if (cell == nil) {
        cell = [[DYCommonSCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cell_Id];
    }
    YXContactsModel *item = self.viewModel.dataArray[indexPath.row];
    [cell bindWithModel:item seletedArray:self.viewModel.seletedPicArray];
    @weakify(self)
    cell.seletedBtnBlock = ^(YXContactsModel *item, BOOL isSelected) {
        @strongify(self)
        if ([self.viewModel.seletedPicArray containsObject:item]) {
                if (isSelected) {return;}
                [self.viewModel.seletedPicArray removeObject:item];
        }else{
             if (!isSelected) {return;}
            [self.viewModel.seletedPicArray addObject:item];
        }
        self.viewModel.seletedCount = self.viewModel.seletedPicArray.count;
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    };

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!self.viewModel.dataArray.count) {return 0.01;}
    return 80;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark --- Event

- (void)leftBarButtonItemDidClick{
    [self.navigationController popViewControllerAnimated:YES];
    kCANoAllInfoManager.dataList = self.orginArray;
    kCANoAllInfoManager.selectAry = self.viewModel.seletedPicArray;
}

- (void)rightBarButtonItemDidClick:(UIButton *)sender{
 
    [self.viewModel.seletedPicArray removeAllObjects];
    if (sender.selected) {
        sender.selected = NO;
//        [self.viewModel.seletedPicArray addObjectsFromArray:self.viewModel.dataArray];
    }else{
        sender.selected = YES;
        [self.viewModel.seletedPicArray addObjectsFromArray:self.viewModel.dataArray];
    }
    [self.tableView reloadData];
    self.viewModel.seletedCount = self.viewModel.seletedPicArray.count;
}

- (void)handleVipTransactionEvent{
    if (kUserManager.userManager.isSubscribe) {
//        NSString *isVipDueDate = [kIAPHelper judgeTimeByStartAndEndTime:kUserManager.userManager.vipDueDate];
//        if ([isVipDueDate isEqualToString:@"过期"]) {
//            RAUserManager *userManager = kUserManager.userManager;
//            userManager.isSubscribe = NO;
//            userManager.vipDueDate = @"";
//
//            if ([kUserManager.userManager.auto_renew_status isEqualToString:@"1"]) {
//                //过期 但是还是处于订阅中 则证明有自动续订
//                //点击自动续费成功 打点
//            }
//            [userManager saveUserData:userManager];
//
//        } else if ([isVipDueDate isEqualToString:@"到期"]) {
//            //点击自动续费成功 打点
//        } else {
//            //未到期
//            [self handleCleanIncompletePhoneEvent];
//        }
    }else{
        [self searchCostEvent];
        return;
    }

    [kIAPHelper addTransactionObserver];
}

- (void)searchCostEvent{
    PBSubscribeViewController *vc = [[PBSubscribeViewController alloc] init];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)handleCleanIncompletePhoneEvent{
    BOOL isSuccess = NO;
    NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:self.viewModel.seletedPicArray];
    for (YXContactsModel *item in  self.viewModel.seletedPicArray) {
        BOOL isOk = [[YXContactsRequestTool shareContactsRequestTool] deleteContactWithModel:item];
        if (isOk) {
            [temp removeObject:item];
            self.viewModel.seletedCount--;
        }
        isSuccess = isOk;
    }
    self.viewModel.seletedPicArray = temp;
    if (isSuccess) {
        NSArray *array = [YXContactsRequestTool shareContactsRequestTool].noSomeInfoContacts;
        kCANoAllInfoManager.dataList = array;
       
        [self.viewModel.dataArray removeAllObjects];
        [self.viewModel.dataArray addObjectsFromArray:array];
        [kCANoAllInfoManager.selectAry removeAllObjects];
        [kCANoAllInfoManager.selectAry addObjectsFromArray:self.viewModel.seletedPicArray];
        [self.tableView reloadData];
    }
}

#pragma mark --- setter/getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = 60;
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _tableView.delaysContentTouches = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
      
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        }
    }
    
    return _tableView;
}

- (IncompleteContactVCModel *)viewModel{
    if (!_viewModel) {
        _viewModel = [[IncompleteContactVCModel alloc] init];
    }
    return _viewModel;
}

- (DYCleanView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[DYCleanView alloc] init];
        _bottomView.hidden = YES;
        _bottomView.userInteractionEnabled = YES;
        @weakify(self)
        _bottomView.cleanBtnBlock = ^{
            @strongify(self)
//            [self handleCleanIncompletePhoneEvent];
            [self handleVipTransactionEvent];
        };
    }
    return _bottomView;
}


@end
